package com.wuhan.template.module.wode.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.widget.RemoteViews;

import com.wuhan.template.R;
import com.wuhan.template.views.IDownload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2016/5/16 0016.
 */
public class DownLoadService extends Service {


    private static final String DOWN_APK_URL = "http://apk.hiapk.com/appdown/com.ss.android.essay.joke";

    // /mnt/sdcard/app_down
    private static final String DW_FILE_PATH = "/app_down";

    // /mnt/sdcard/app_down/upgrade.apk
    private static final String DW_FILE_NAME = "upgrade.apk";

    // 通知管理器
    private NotificationManager notificationManager;

    // 是否正在下载
    private boolean isDownloading = true;

    @Override
    public void onCreate() {
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    private class MyBinder extends Binder implements IDownload {

        @Override
        public void download() {
            startUpNotification();
            new Thread() {
                @Override
                public void run() {
                    downFile();
                }
            }.start();
        }


        @Override
        public void cancelDownload() {

            stopSelf();
        }
    }


    private Notification notification;

    private void startUpNotification() {
        notification = new Notification();
        notification.when = System.currentTimeMillis();
        // 常驻在正在运行栏中
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.tickerText = "有版本更新";
        notification.icon = R.mipmap.ic_launcher;

        // 自定义通知布局
        RemoteViews remoteViews =
                new RemoteViews(getPackageName(), R.layout.notifiy_layout);
        remoteViews.setTextViewText(R.id.appName, "App正在下载中...");
        remoteViews.setTextViewText(R.id.app_progress, "0%");
        remoteViews.setProgressBar(R.id.progressbar, 100, 0, false);
        // 设置自定义通知布局
        notification.contentView = remoteViews;

        notificationManager.notify(100, notification);

    }

    private void downFile() {

        String filePath = null;
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        //   /mnt/sdcard
            filePath = Environment.getExternalStorageDirectory().getPath();
        }else {
            // /data/data/<package_name>/cache
            filePath = getCacheDir().getPath();
        }
        filePath += DW_FILE_PATH;
        File file = new File(filePath);
    if(!file.exists()){
        file.mkdirs();
    }
        file = new File(filePath+DW_FILE_NAME);
        if(file.exists()){
            file.delete();
        }


        HttpURLConnection conn = null;
        InputStream in = null;
        FileOutputStream fout = null;
        try
        {
            URL url = new URL(DOWN_APK_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(120 * 1000);
            conn.connect();

            int responseCode = conn.getResponseCode();

            if (responseCode == 200)
            {
                in = conn.getInputStream();
                fout = new FileOutputStream(file.getPath());
                // 缓冲流
                BufferedOutputStream bout = new BufferedOutputStream(fout);

                int len = -1;
                byte[] buffer = new byte[1024 * 10];

                // 文件总的大小
                long totalLength = conn.getContentLength();
                // 当前读取大小
                long currentLen = 0;
                // 读取比例
                int rate = 0;

                while (isDownloading)
                {
                    len = in.read(buffer);

                    if (len <= 0)
                    {
                        // 已经读取完毕
                        Message msg = handler.obtainMessage();
                        msg.what = WHAT_FINISH;
                        msg.obj = file.getPath();
                        handler.sendMessage(msg);
                        break;
                    }

                    currentLen += len;
                    rate = (int)((currentLen * 100) / totalLength);

                    // 写入文件，并且提示通知进度
                    bout.write(buffer, 0, len);

                    // 通知主线程提示通知，提示下载进度
                    Message msg = handler.obtainMessage();
                    msg.what = WHAT_PROGRESS;
                    msg.arg1 = rate;
                    handler.sendMessage(msg);
                }
            } }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }


    private static final int WHAT_PROGRESS = 1;
    private static final int WHAT_FINISH = 2;

    public Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                // 还在下载
                case WHAT_PROGRESS:
                    int rate = msg.arg1;
                    RemoteViews remoteViews = notification.contentView;
                    remoteViews.setTextViewText(R.id.app_progress, rate + "%");
                    remoteViews.setProgressBar(R.id.progressbar, 100, rate, false);
                    notificationManager.notify(100, notification);
                    // 先取消之前发送的消息
                    handler.removeMessages(WHAT_PROGRESS);
                    break;
                // 下载完毕
                case WHAT_FINISH:

                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notificationManager.cancel(100);

                    String filePath = (String) msg.obj;

                    // 安装
                    installApk(filePath);

                    break;
            }
        }
    };

    private void installApk(String filePath)
    {
        File file = new File(filePath);
        if (!file.exists())
        {
            stopSelf();
            return;
        }

        // 安装
        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.setDataAndType(
                Uri.parse("file://" + filePath), "application/vnd.android.package-archive");

        startActivity(intent);

        // 关闭服务本身
        stopSelf();
    }


    @Override
    public void onDestroy()
    {
        super.onDestroy();

        isDownloading = false;
        handler.removeCallbacksAndMessages(null);
        notificationManager.cancel(100);

    }
}
